package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.PermissionDAO;
import com.dao.RoleDAO;
import com.pojo.Permission;
import com.pojo.ResponseBody;
import com.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Service
public class PermissionService extends ServiceImpl<PermissionDAO, Permission> {

    @Autowired
    private PermissionDAO permissionMapper;

    @Autowired
    private RoleDAO roleMapper;

    /**
     * 根据用户名获取权限
     * @param username
     * @return
     */
    public List getPermissionByUser(String username) {
        if ("admin".equals(username)){
            List<Permission> list =  permissionMapper.selectList(null);
            List urls = new ArrayList();
            if (list!=null) {
                for (Permission p : list) {
                    if (p.getPermissionUrl()!=null && p.getPermissionUrl().trim().length()>0)
                    {
                        urls.add(p.getPermissionUrl());
                    }
                }
            }
            return urls;
        }
        List<String> list = permissionMapper.getPermissionByUsername(username);
        List urls = new ArrayList();
        for (String url: list){
            if (url!=null && url.trim().length()>0)
            {
                urls.add(url);
            }
        }
        return urls;
    }

    /**
     * 跟据角色id查所有权限
     * @param roleId
     * @return
     */
    public Map findPermissionByRole(String roleId) {
        List<Map> list = permissionMapper.findPermissionByRole();
        ResponseBody rootResponsBody = setFirstData(list);
        List responseBodys = add(list, rootResponsBody);

        Map map = new HashMap();
        map.put("data", responseBodys);
        List listArray = permissionMapper.findPermissionIdByRole(roleId);
        map.put("array", listArray);
        return map;
    }

    /**
     * 求根节点下所有子节点
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    public List<ResponseBody> setData(List<Map> list, ResponseBody b) {
        List<ResponseBody> responseBodys = new ArrayList<ResponseBody>();
        for (Map m : list) {
            if (b.getId().equals(m.get("permission_parent_id").toString())) {
                ResponseBody responseBody = new ResponseBody();
                responseBody.setId(m.get("permission_id").toString());
                if (m.get("permission_menu_name") != null) {
                    responseBody.setTitle(m.get("permission_menu_name").toString());
                } else {
                    responseBody.setTitle("未命名");
                }
                responseBody.setEnd(Boolean.getBoolean(m.get("permission_end").toString()));
                responseBodys.add(responseBody);
            }
        }
        return responseBodys;
    }

    /**
     * 求根节点
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    public ResponseBody setFirstData(List<Map> list) {

        for (Map m : list) {
            ResponseBody responseBody = new ResponseBody();

            if (0 == Long.parseLong(m.get("permission_parent_id").toString())) {
                responseBody.setId(m.get("permission_id").toString());
                responseBody.setTitle(m.get("permission_menu_name").toString());
                return responseBody;
            }
        }
        throw new RuntimeException("not found root node!");
    }

    /**
     * 判断是否有子节点，有子节点则循环子节点
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    public List<ResponseBody> add(List<Map> list, ResponseBody root) {
        List<ResponseBody> responseBodyAll = new ArrayList<ResponseBody>();
        //查当前节点的子节点
        List<ResponseBody> responseBodys2 = setData(list, root);
        //如果子节点有数据，则再次循环子节点
        if (responseBodys2.size() != 0) {
            responseBodyAll.add(root);
            root.setChildren(responseBodys2);
            for (int j = 0; j < responseBodys2.size(); j++) {
                add(list, responseBodys2.get(j));
            }
        }
        return responseBodyAll;
    }

    /**
     * 根据用户保存或删除权限
     * @param permissionArray
     * @param roleId
     * @return
     */
    public int saveOrDelPermissionByRole(String permissionArray, String roleId) {
        permissionMapper.delPermissionByRole(roleId);
        if (permissionArray != null) {
            int n = permissionMapper.savePermissionWithRole(permissionArray.split(","), roleId);
            return n;
        }
        return 0;
    }

    /**
     * 查所有权限
     * @return
     */
    public Map findPermission() {
        List<Map> list = permissionMapper.findPermissionByRole();
        ResponseBody rootResponsBody = setFirstData(list);
        List responseBodys = add(list, rootResponsBody);

        Map map = new HashMap();
        map.put("data", responseBodys);
        return map;
    }

    /**
     * 新增角色和角色的权限
     * @param permissionIdArray
     * @param rolename
     * @return
     */
    public int savePermission(String[] permissionIdArray, String rolename) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        queryWrapper.eq("role_name", rolename);
        List<Role> roles = roleMapper.selectList(queryWrapper);
        Role role = null;
        if (roles.size() == 0) {
            role = new Role();
        } else {
            return 0;
        }
        role.setRoleName(rolename);
        int n = roleMapper.insert(role);
        String id = "-1";
        if (n > 0) {
            id = role.getRoleId();
            if (permissionIdArray != null) {
                int n1 = permissionMapper.savePermissionWithRole(permissionIdArray, id);
                return n1;
            } else {
                return 1;
            }
        }
        return 0;
    }

    public int permissionInsert(String url, String text, String end, String pid) {
        Permission permission = new Permission();
        permission.setPermissionParentId(pid);
        permission.setPermissionMenuName(text);
        permission.setPermissionUrl(url);
        permission.setPermissionEnd(end);
        permission.setPermissionParentId(pid);
        int n = permissionMapper.insert(permission);
        return n;
    }

    public int permissionUpdate(String id, String text, String url, String end) {
        Permission permission = permissionMapper.selectById(id);
        permission.setPermissionMenuName(text);
        permission.setPermissionUrl(url);
        permission.setPermissionEnd(end);
        int n = permissionMapper.updateById(permission);
        return n;
    }

    public Map findUrlById(String id) {
        Map map = permissionMapper.findUrlById(id);
        return map;
    }

    public int delById(String id) {
        return permissionMapper.deleteById(id);
    }

    /**
     * 根据url查询菜单名称
     * @param url
     * @return
     */
    public String getPermissionByUrl(String url) {
        List<Permission> url1 = permissionMapper.selectList(new QueryWrapper<Permission>().eq("permission_url", url));
        if(url1.size() == 0) {
            return null ;
        }
        return url1.get(0).getPermissionMenuName() ;
    }
}